package com.hwpt.hwaccount.feature.splash;

import android.content.Context;
import com.hwpt.hwaccount.core.data.local.entity.UserEntity;
import com.hwpt.hwaccount.core.data.repository.UserInfoRepository;

import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers;
import io.reactivex.rxjava3.disposables.CompositeDisposable;
import io.reactivex.rxjava3.observers.DisposableSingleObserver;
import io.reactivex.rxjava3.schedulers.Schedulers;
import java.util.List;

/**
 * 引导页Model层实现，负责与数据仓库交互
 */
public class SplashModel implements SplashContract.Model {

    private final UserInfoRepository userInfoRepository;
    private final CompositeDisposable compositeDisposable;

    public SplashModel(Context context) {
        this.userInfoRepository = new UserInfoRepository(context);
        this.compositeDisposable = new CompositeDisposable();
    }

    @Override
    public void getAllUsers(OnUserInfoCallback callback) {
        compositeDisposable.add(
            userInfoRepository.getAllUsers()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribeWith(new DisposableSingleObserver<List<UserEntity>>() {
                    @Override
                    public void onSuccess(List<UserEntity> userEntities) {
                        callback.onSuccess(userEntities);
                    }

                    @Override
                    public void onError(Throwable e) {
                        callback.onError(e);
                    }
                })
        );
    }

    /**
     * 清除RxJava订阅，防止内存泄漏
     */
    public void dispose() {
        compositeDisposable.dispose();
    }
}
